//
//  MySigleInfomationViewController.m
//  VEMoneyPorject
//
//  Created by 陈建 on 2018/9/24.
//  Copyright © 2018年 陈建. All rights reserved.
//

#import "MySigleInfomationViewController.h"
#import "MySIEdietPhotoTableViewCell.h"
#import "MyInputNameTextFieldTableViewCell.h"
#import "MyChangeNiChengLableViewController.h"
#import "DTLongButtonView.h"
#import "VERealNameViewController.h"
@interface MySigleInfomationViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    BOOL _hasPhoto;//是否是 相册/拍照中的图片
    NSString *_imgageData;
}
@property (nonatomic, strong) UIImage *photoImage;//头像
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@end

@implementation MySigleInfomationViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self cj_reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.isSuccessNet = YES;
    // Do any additional setup after loading the view.
}

- (NSInteger)cj_numberOfSections{
    return 1;
}

- (NSInteger)cj_numberOfRowsInsection:(NSInteger)section{
    return 3;
}

- (CGFloat)cj_cellHeightAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
- (CGFloat)cj_sectionFooterHeightAtSection:(NSInteger)section{
     return 400;
}

- (UIView *)cj_footerAtSection:(NSInteger)section{
    DTLongButtonView *view = [DTLongButtonView shareView];
    [view.tapBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    view.tapBtnBlock = ^{
        NSLog(@"确 定");
        [[CJUserInfoManager sharedManager] didLoginOut];
        self.logOutSuccessBlock();
        [self pop];
        
    };
    return view;
}

- (CJBaseTableViewCell *)cj_cellAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        MySIEdietPhotoTableViewCell *cell = [MySIEdietPhotoTableViewCell nibWithTableView:self.tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.bigImageView.layerCornerRadius = 25;
        cell.titleLable.text = @"头像";
        cell.titleLable.textColor = [UIColor colorWithHexString:kNomalTextBlackColor];
        if (_imgageData.length == 0 && _hasPhoto == NO) {
            [cell.bigImageView setImageWithUrlString:[CJUserInfoManager sharedManager].currentUserInfo.PHOTO palceHolderImage:[UIImage imageNamed:@"头像"]];
        }else{
            cell.bigImageView.image = self.photoImage;
        }
        
        return cell;
    }
    if (indexPath.row == 1) {
        MyInputNameTextFieldTableViewCell *cell = [MyInputNameTextFieldTableViewCell nibWithTableView:self.tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLable.textColor = [UIColor colorWithHexString:kNomalTextBlackColor];
        cell.titleLable.text = @"昵称";
        cell.detailTextField.placeholder = @"请输入昵称";
        cell.detailTextField.enabled = NO;
        cell.detailTextField.textColor = [UIColor colorWithHexString:kDetailTextBlackColor];
        cell.detailTextField.text = [CJUserInfoManager sharedManager].currentUserInfo.USERNAME;
        return cell;
    }
    if (indexPath.row == 2) {
        MyInputNameTextFieldTableViewCell *cell = [MyInputNameTextFieldTableViewCell nibWithTableView:self.tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLable.textColor = [UIColor colorWithHexString:kNomalTextBlackColor];
        cell.titleLable.text = @"实名认证";
        cell.detailTextField.enabled = NO;
        cell.detailTextField.textColor = [UIColor colorWithHexString:kDetailTextBlackColor];
      
        if ([[CJUserInfoManager sharedManager].currentUserInfo.STATE isEqualToString:@"已认证"]) {
              cell.detailTextField.text = @"已认证";
        }else if ([[CJUserInfoManager sharedManager].currentUserInfo.STATE isEqualToString:@"审核失败"]){
              cell.detailTextField.text = @"审核失败";
        }else if ([[CJUserInfoManager sharedManager].currentUserInfo.STATE isEqualToString:@"待审核"]){
            cell.detailTextField.text = @"待审核";
        }else{
            cell.detailTextField.text = @"未实名认证";
        }
        
        return cell;
    }
    
    return nil;
}

- (void)cj_didSelectCellAtIndexPath:(NSIndexPath *)indexPath cell:(CJBaseTableViewCell *)cell{
    if (indexPath.row == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        //了解更多:style:UIAlertActionStyleDestructive
        UIAlertAction *clearAction1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //清空缓存
            NSLog(@"相册");
            [self selectImageFromAlbum];
        }];
        UIAlertAction *clearAction2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //清空缓存
            NSLog(@"拍照");
            [self selectImageFromCamera];
        }];
        [alertController addAction:clearAction1];
        [alertController addAction:clearAction2];
        
        //取消:style:UIAlertActionStyleCancel
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    if (indexPath.row == 1) {
        MyChangeNiChengLableViewController *vc = [[MyChangeNiChengLableViewController alloc] init];
        vc.title = @"修改昵称";
        [self pushVc:vc];
    }
    if (indexPath.row == 2) {
        if ([[CJUserInfoManager sharedManager].currentUserInfo.STATE isEqualToString:@"已认证"] || [[CJUserInfoManager sharedManager].currentUserInfo.STATE isEqualToString:@"待审核"]) {
        }else{
            VERealNameViewController *vc = [VERealNameViewController new];
            vc.DataSuccessBlock = ^{
                [self cj_reloadData];
            };
            [self pushVc:vc];
        }
        
    }
}
-(UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        
        _imagePickerController.delegate = self;
        _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}
#pragma mark 从相册获取图片或视频
- (void)selectImageFromAlbum {
    //NSLog(@"相册");
    self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:self.imagePickerController animated:YES completion:nil];
}

#pragma mark 从摄像头获取图片
- (void)selectImageFromCamera {
    self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    //相机类型（拍照、录像...）字符串需要做相应的类型转换
    self.imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    
    //设置摄像头模式（拍照，录制视频）为录像模式
    self.imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    [self presentViewController:self.imagePickerController animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
// 拍照完成回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        self.photoImage = info[UIImagePickerControllerEditedImage];
        _hasPhoto = YES;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
        
        NSData *fileData = UIImageJPEGRepresentation(self.photoImage, 1.0);
        /*
         //保存到相册
         UIImageWriteToSavedPhotosAlbum(self.photoImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
         */
        //上传图片
        [self uploadImageWithData:fileData];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)uploadImageWithData:(NSData *)data{

    
    NSMutableArray *imageArr = [NSMutableArray new];
    
    //缩略图
    NSData *photoImageData = UIImageJPEGRepresentation(self.photoImage, 0.3);

    
    [imageArr addObject:photoImageData];

    NSDictionary *parameters = @{@"Userid":[CJUserInfoManager sharedManager].currentUserInfo.USERID};
    
    [self uploadMessaaageBtn:parameters imageDataArray:imageArr];
    
}



- (void)uploadMessaaageBtn:(NSDictionary *)dicParams imageDataArray:(NSArray *)imageDataArr{
   NSString *path = [NSString stringWithFormat:@"%@/VEService/EditUserPhoto.do",kPublicInterfaceAPI];
    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:path isPost:YES withParameters:dicParams];
    request.cj_imageArray =  imageDataArr;
    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
        
        NSLog(@"%@",response);
        [CJUIKit showSuccessWithStatus:message];
        
    }];



 

                                                                      
    
 
    
}



//取消返回
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    _hasPhoto = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
